import { Request, Response } from 'express';
import { AuthRequest } from '../types';
import Team from '../models/Team';
import User from '../models/User';

export const createTeam = async (req: AuthRequest, res: Response) => {
    const { name, description } = req.body;
    const creator = req.user;
    if (!name) { return res.status(400).json({ message: 'Team name is required' }); }
    if (!creator) { return res.status(401).json({ message: 'Not authorized' }); }

    try {
        const team = await Team.create({
            name,
            description,
            owner: creator._id,
            members: [creator._id], 
        });
        await User.findByIdAndUpdate(creator._id, { $push: { teams: team._id } });
        res.status(201).json(team);
    } catch (error) { 
        console.error(error);
        res.status(500).json({ message: 'Server Error' }); 
    }
};

export const addMemberToTeam = async (req: AuthRequest, res: Response) => {
    const { email } = req.body;
    const teamId = req.params.id;
    const inviter = req.user;

    try {
        if (!inviter) { return res.status(401).json({ message: 'Not authorized' }); }

        const team = await Team.findById(teamId);
        if (!team) { return res.status(404).json({ message: 'Team not found' }); }

        // 【FIX】Apply type assertion to both sides of the comparison
        if ((team.owner as any).toString() !== (inviter as any)._id.toString()) {
            return res.status(403).json({ message: 'Forbidden: Only the team owner can add members' });
        }

        const userToAdd = await User.findOne({ email });
        if (!userToAdd) { return res.status(404).json({ message: 'User with this email not found' }); }

        if (team.members.some((memberId: any) => memberId.equals(userToAdd._id))) {
            return res.status(400).json({ message: 'User is already in the team' });
        }

        team.members.push(userToAdd._id);
        userToAdd.teams.push(team._id);

        await team.save();
        await userToAdd.save();

        const populatedTeam = await team.populate('members', 'username email');
        res.json(populatedTeam);

    } catch (error) { 
        console.error(error);
        res.status(500).json({ message: 'Server Error' }); 
    }
};

export const getTeams = async (req: Request, res: Response) => {
    try {
        const teams = await Team.find({}).populate('members', 'username email');
        res.json(teams);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};